package com.example.learn.utile;

import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;

public class TimeUtil {
    //获取当前时间 String
    public static  String  getCurrentTime(){
        Date date=new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return  simpleDateFormat.format(date);
    }
    //获取当前时间 Date
    public static Date getCurrentDate(){
        Date date=new Date();
        return  date;
    }

    //把数据库时间转为String
    public static String changeDateToStr(Date date){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       String dateStr= simpleDateFormat.format(date);
        return  dateStr;
    }
    //获取俩个时间的相差天数
    public static long between_days(Date time1, Date time2) {

        Calendar cal = Calendar.getInstance();
        cal.setTime(time1);
        long time11 = cal.getTimeInMillis();
        cal.setTime(time2);
        long time22 = cal.getTimeInMillis();
        long between_days=(time22-time11)/(10003600*24);

        return between_days;
    }
    /**
     * java 8 获取当前月的开始和结束时间
     */
    public static String getfirstDay(String queryTime) {

        String strDate = queryTime+"-01";
        LocalDate localDate=   stringToLocalDate(strDate);
        //本月的第一天
        LocalDate  firstDay= LocalDate.of(localDate.getYear(), localDate.getMonth(), 1);
        return firstDay.toString();


    }
    /**
     * java 8 获取当前月的开始和结束时间
     */
    public static String getlastDay(String queryTime) {

        String strDate = queryTime+"-01";
        LocalDate localDate=   stringToLocalDate(strDate);


        //本月的最后一天
        LocalDate lastDay = localDate.with(TemporalAdjusters.lastDayOfMonth());
        return lastDay.toString();
    }
    /**
     * 字符串格式化,字符串必须符合 yyyy-MM-dd 格式,当字符串非法时,例如 201s-00-35 时,返回 null
     *
     * @param strDate 将要 LocalDate 化的字符串
     * @return LocalDate
     */
    public static LocalDate stringToLocalDate(String strDate) {
        DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate=      LocalDate.parse(strDate, dateTimeFormatter2);
       return localDate;
    }


}
